<template>
	<div class="wrapper">
		<top-bar>
			<template v-slot:title>
				{{ $t("Mobile phone recharge") }}
			</template>
		</top-bar>
		<abnormal-page v-if="pageError" @retry="getRechargeInfo"></abnormal-page>
        <div v-else class="container">
			<div class="main">
				<div class="balance-panel">
					<div class="title">{{ $t("Balance") }}</div>
					<div class="coin-box">
						<img
							class="icon-coin"
							src="../../assets/images/icon_coin.svg"
						/>
						{{ vueState.pageInfo.totalCoin }}
					</div>
				</div>
				<div class="input-panel">
					<div class="area-number">+{{ areaCode }}</div>
					<unique-input
						v-model:input="inputData.phoneNumber"
						v-model:state="inputData.phoneNumberState"
						:placeholder="$t('Enter your Phone number')"
						:maxLength="20"
						:valid="isNumber"
						:successInfo="$t(inputData.successInfo)"
						:errorInfo="$t(inputData.errorInfo)"
						:clear="true"
					></unique-input>
				</div>
				<div class="select module">
					<div class="header">
						<div class="title">
							{{ $t("Please select denomination") }}
						</div>
					</div>
					<div class="main">
						<div class="select-list">
							<div
								v-for="(item, index) in rateList"
								:key="index"
								:class="[
									'select-list-item',
									{ active: selectActive === index },
								]"
								@click="selectItem(item, index)"
							>
								<div class="main">
									<div class="money">
										<span class="monetary-unit">{{
											vueState.countryInfo.monetaryUnit
										}}</span
										>{{ item.money }}
									</div>
								</div>
								<div class="footer">
									<div class="coin-num">{{ item.coin }}</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="rule module">
					<div class="header">
						<div class="title">{{ $t("Rule description") }}:</div>
					</div>
					<div class="main">
						<!-- <div class="text">
							1.
							{{
								$t("phoneRechargeRules1")(
									`${vueState.countryInfo.monetaryUnit} ${
										vueState.countryInfo.country === "BR"
											? "15.00"
											: "100.00"
									}`
								)
							}}.
						</div> -->
						<div class="text">1. {{$t('The phone bill only supports recharges above $m',[{msg:'$m',val:`${vueState.countryInfo.monetaryUnit} ${vueState.countryInfo.country === 'BR' ? '15.00' : '100.00'}`}])}}.</div>
						<div class="text">
							2.
							{{
								$t(
									"The phone bill will be recharged within 48 hours at the earliest"
								)
							}}.
						</div>
					</div>
				</div>
			</div>
			<div class="footer">
				<div
					class="button"
					:style="{
						bottom:
							0.32 * fsize +
							(vueState.pageStyle.tabBarHeight || 0) +
							'px',
					}"
					@click="clickRecharge"
				>
					{{ $t("Recharge now") }}
				</div>
			</div>
		</div>
	</div>
</template>
<script>
import { getCurrentInstance, inject, onMounted, reactive, toRefs,computed } from 'vue'
import {BalanceApi} from '@@/api/api.js'
import uniqueInput from '../../components/Input/index.vue'
import FailureModal from './modal/failureModal.vue'
import {isNumber,checkObjectEmpty} from '@@/utils/common.js'
import { Toast } from 'vant'
import { useRouter } from 'vue-router'

export default {
    components:{
        uniqueInput,
        FailureModal,
    },
    props:{
        channel:{
            default:'{}'
        }
    },
    setup(props) {
        const router = useRouter()
        const {proxy} = getCurrentInstance()
        const vueState = inject('vueState')
        const state = reactive({
            pageError:false,
            fsize:window.fsize,
            selectActive:0,
            areaCode:'',
            rateList:[]
        })
        const inputData = reactive({
            phoneNumber:'',
            phoneNumberState:false,
            successInfo:'Success! Number is available!',
            errorInfo:'Error! Number is not available!',
        })
        const channelInfo = computed(()=>{
            return checkObjectEmpty(JSON.parse(props.channel)) ? vueState.pageInfo.withdrawChannel : JSON.parse(props.channel)
        })
        const failureModalData = reactive({
            show:false,
        })
        const getRechargeInfo = async()=> {
            Toast.loading({duration:0,message:`${proxy.$t('Loading')}...`})
            try{
                const {areaCode,toBalanceRate:{channelRateVos=[]}} = await BalanceApi.RechargeInfo({channelType:channelInfo.value?.type})
                state.pageError = false
                state.areaCode = areaCode
                state.rateList = channelRateVos.map((item)=>{
                    const obj = {
                        coin:item.coin,
                        money:(item.money / 100).toFixed(2)
                    }
                    return obj
                })
                console.log(state.rateList);
                Toast.clear()
            }catch(e){
                state.pageError = true
                console.log(e);
                setTimeout(()=>{
                    Toast.clear()
                },3000)
            }
            
        }
        const clickRecharge = async()=>{
            if(!vueState.pageInfo.mobile){
                window.SDKPostMessage({
                    event:'h5_open_page',
                    data:{
                        target:'bind_mobile',
                        data:{
                            page:'withdrawpage',
                            showEvent:'showwithdrawbind',
                            clickEvent:'clickwithdrawbind'
                        }
                    }
                })
                window.trackEvent({pageTitle:'rechargePage',ev:'clickRechargeButton'})
                return
            }
            if(vueState.pageInfo.totalCoin < state.rateList[state.selectActive].coin){
                Toast(proxy.$t('Your balance is insufficient'))
                window.trackEvent({pageTitle:'rechargePage',ev:'clickRechargeButton',remarks:'status:insufficient'})
                return
            }
            if(!channelInfo.value.flag){
                failureModalData.show = true
                window.trackEvent({pageTitle:'withdrawpage',ev:'showSwitchingPop',remarks:`Type=${channelInfo.value.type}`})
                return
            }
            if(!inputData.phoneNumberState){
                Toast(proxy.$t('Please enter your Phone number'))
                return
            }
            try{
                await BalanceApi.Recharge({
                    bundleId:vueState.bundle,
                    tel:inputData.phoneNumber,
                    amount:state.rateList[state.selectActive].coin,
                    type:channelInfo.value.type,
                    channelId:channelInfo.value.channelId
                })
                window.trackEvent({pageTitle:'rechargePage',ev:'clickRechargeButton',remarks:'status:success'})
                window.SDKPostMessage({
                    event:'h5_open_page',
                    data:{
                        target:'reward_pop',
                        data:{
                            from:'recharge',
                            coin:0,
                            cash:0
                        }
                    }
                })
            }catch(e){
                window.trackEvent({pageTitle:'rechargePage',ev:'clickRechargeButton',remarks:'status:others'})
                if(e?.data?.code === 201022){
                    Toast.clear()
                    failureModalData.show = true
                    window.trackEvent({pageTitle:'withdrawpage',ev:'showSwitchingPop',remarks:`Type=${channelInfo.value.type}`})
                }
                console.log(e);
            }
        }
        const selectItem = (item,index)=> {
            state.selectActive = index
            window.trackEvent({pageTitle:'rechargePage',ev:'clickRechargeGear',remarks:`${vueState.countryInfo.monetaryUnit}${item.money}`})
        }
        const goWithdrawHistory = ()=> {
            if(!vueState.pageInfo.mobile){
                window.SDKPostMessage({
                    event:'h5_open_page',
                    data:{
                        target:'bind_mobile',
                        data:{
                            page:'withdrawpage',
                            showEvent:'showwithdrawbind',
                            clickEvent:'clickwithdrawbind'
                        }
                    }
                })
                return
            }
            router.push({name:'withdrawRecord'})
        }
        onMounted(()=>{
            console.log(channelInfo.value);
            window.trackEvent({pageTitle:'rechargePage',ev:'showPage'})
            vueState.EventEmitter.immediately('afterRegist',getRechargeInfo,vueState.pageStatus.afterRegist)
        })
        return {
            ...toRefs(state),
            vueState,
            inputData,
            isNumber,
            clickRecharge,
            selectItem,
            getRechargeInfo,
            failureModalData,
            goWithdrawHistory
        }
    }
}
</script>
<style lang="less" scoped>
.wrapper {
	height: 100%;
	.icon-coin {
		height: 0.24rem;
		width: 0.24rem;
		margin-right: 2px;
	}
	.coin-num {
		background: url(../../assets/images/icon_coin.svg) no-repeat left center;
		background-size: 0.24rem 0.24rem;
		padding-left: 0.26rem;
		line-height: 0.24rem;
	}
	.container {
		height: 100%;
		overflow-y: auto;
		padding: 0.16rem 0.16rem;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		& > .main {
			flex-shrink: 0;
			.module {
				margin-top: 0.24rem;
				.title {
					font-size: 0.16rem;
					font-weight: 500;
					color: #121314;
					line-height: 0.28rem;
				}
			}
			.balance-panel {
				.ys();
				.aic;
				.title {
					font-size: 0.14rem;
					font-weight: 400;
					color: rgba(136, 136, 136, 0.72);
					margin-bottom: 0.08rem;
				}
				.coin-box {
					height: 0.42rem;
					font-size: 0.32rem;
					font-weight: 700;
					color: #222222;
					letter-spacing: 0px;
					.xs;
					.aic;
				}
			}
			.input-panel {
				margin-top: 0.56rem;
				display: flex;
				align-items: flex-start;
				.area-number {
					flex-shrink: 0;
					height: 0.44rem;
					width: 0.44rem;
					border-radius: 0.1rem;
					background-color: #fefaf4;
					margin-right: 0.08rem;
					color: #8f9bba;
					font-size: 0.14rem;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
			.select {
				& > .main {
					margin-top: 0.08rem;
					.select-list {
						display: flex;
						align-items: center;
						justify-content: space-between;
						&-item {
							height: 1.12rem;
							width: 1.66rem;
							background: url(../../assets/images/recharge_select_bg_green.png)
								no-repeat center;
							background-size: contain;
							position: relative;
							&.active {
								&::after {
									background-image: url(../../assets/images/recharge_select_active.png);
								}
							}
							&::after {
								position: absolute;
								right: 0;
								top: 0;
								content: "";
								display: block;
								height: 0.26rem;
								width: 0.32rem;
								background: url(../../assets/images/recharge_select_unactive.png)
									no-repeat center;
								background-size: contain;
							}
							&:last-child {
								background-image: url(../../assets/images/recharge_select_bg_yellow.png);
								.coin-num {
									color: #ffffff;
								}
							}
							.coin-num {
								color: #ffffff;
							}
							& > .main {
								height: 0.72rem;
								width: 100%;
								color: white;
								font-weight: 700;
								display: flex;
								align-items: center;
								justify-content: center;
								.money {
									font-size: 0.24rem;
									.monetary-unit {
										display: inline-block;
										font-size: 0.16rem;
									}
								}
							}
							& > .footer {
								height: 0.4rem;
								width: 100%;
								font-weight: 700;
								font-size: 0.18rem;
								display: flex;
								align-items: center;
								justify-content: center;
							}
						}
					}
				}
			}
			.rule {
				& > .main {
					margin-top: 0.12rem;
					color: #9c9da6;
					font-size: 0.12rem;
					font-weight: 400;
					.text {
						line-height: 0.2rem;
						margin-bottom: 0.08rem;
					}
				}
			}
		}
		& > .footer {
			flex-shrink: 0;
			.button {
				.unique-button();
				font-size: 0.16rem;
				width: 100%;
				height: 0.46rem;
				border-radius: 0.12rem;
				// position: fixed;
				// // bottom: .32rem;
				// left: 50%;
				// transform: translateX(-50%);
			}
		}
	}
}
</style>